import {Component, ViewChild} from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  @ViewChild('b')
  deleteConfirmationDialog;

  showDialog = false;
  showDeleteConfirmation = false;
  editingTodo: any = null;
  fieldValue = '';
  todoList: any = [];
  okButtonText = 'Create task';

  // private indexToDelete: number;
  log(text) {
    console.log(text);
  }
  // changeVisible(visible) {
  //   this.showDialog = visible;
  // }
  openTodoDialog(todo = null) {
    this.okButtonText = 'Create task';
    this.fieldValue = '';
    this.editingTodo = todo;
    if (todo) {
      this.fieldValue = todo.title;
      this.okButtonText = 'Edit task';
    }
    this.showDialog = true;
  }
  openDeleteConfirmationDialog(todo, indexToDelete) {
    this.okButtonText = 'Yes';
    this.fieldValue = todo.title;
    this.showDeleteConfirmation = true;
    this.deleteConfirmationDialog.tag = indexToDelete;
    this.deleteConfirmationDialog.value = todo.title;
  }
  remove(title) {
    if (title != null) {
      const indexToDelete = this.deleteConfirmationDialog.tag;
      this.todoList.splice(indexToDelete, 1);
    }
    this.hideDialog();
  }
  updateTodo(title) {
    if (title) {
      title = title.trim();
      if (this.editingTodo) {
        this.editTodo(title);
      } else {
        this.addTodo(title);
      }
    }
    this.hideDialog();
  }
  editTodo(title) {
    this.editingTodo.title = title;
  }
  addTodo(title) {
    const todo = {title: title, completed: false};
    this.todoList.push(todo);
  }
  hideDialog() {
    this.showDeleteConfirmation = false;
    this.showDialog = false;
    this.editingTodo = null;
    this.fieldValue = null; // make sure Input is new
  }
}
